//
//  BMActionSheet.m
//  bigmama
//
//  Created by huyuchen on 2017/8/23.
//  Copyright © 2017年 盛成文化. All rights reserved.
//

#import "BMActionSheet.h"
#import "BMActionAlertCell.h"

@interface BMActionSheet () <UITableViewDelegate,UITableViewDataSource>
//tableView
@property (nonatomic, strong) UITableView *tableView;
//遮罩层点击
@property (nonatomic, strong) UIControl *overlayControl;
//数据源
@property (nonatomic, strong) NSArray *dataArray;
//图片数组
@property (nonatomic, strong) NSArray *imageArray;
//高亮下标
@property (nonatomic, assign) NSInteger specialIndex;
//标题
@property (nonatomic, copy) NSString *title;
//点击回调
@property (nonatomic, copy) ButtonClickBlock clickBlock;
//样式
@property (assign, nonatomic) BMActionSheetStyle viewStyle;
@end

@implementation BMActionSheet

+ (instancetype)sharedActionSheet{
    BMActionSheet *as = [[self alloc] init];
    as.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
    return as;
}

+ (void)showActionSheetWithStyle:(BMActionSheetStyle)style
                    contentArray:(NSArray<NSString *> *)contentArray
                      imageArray:(NSArray<UIImage *> *)imageArray
                    specialIndex:(NSInteger)specialIndex
                           title:(NSString *)title
                   configuration:(void(^)(BMActionSheet *view))configuration
                clickButtonIndex:(ButtonClickBlock)clickButtonIndex{
    BMActionSheet *as = [self sharedActionSheet];
    as.dataArray = contentArray;
    as.clickBlock = clickButtonIndex;
    as.viewStyle = style;
    as.specialIndex = specialIndex;
    as.title = title;
    as.imageArray = imageArray;
    if (configuration) {
        configuration(as);
    }
    [as.tableView reloadData];
    [as show];
}

+ (void)showDeleteActionSheetWithTitle:(NSString *)title configuration:(void(^)(BMActionSheet *view))configuration clickBUttonIndex:(ButtonClickBlock)clickButtonIndex{
    BMActionSheet *as = [self sharedActionSheet];
    as.viewStyle = BMActionSheetStyleTitle;
    as.title = title?:@"删除状态后将不可恢复,确认要删除?";
    as.dataArray = @[@"删除"];
    as.clickBlock = clickButtonIndex;
    // index 0标题 1删除 2取消
    as.specialIndex = 1;
    if (configuration) {
        configuration(as);
    }
    [as.tableView reloadData];
    [as show];
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        if (self.viewStyle == BMActionSheetStyleNormal || self.viewStyle == BMActionSheetStyleImage) {
            return self.dataArray.count;
        }
        else {
            return self.dataArray.count + 1;
        }
    }
    else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BMActionAlertCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BMActionAlertCell class]) forIndexPath:indexPath];
    cell.selectionStyle = (self.title)?UITableViewCellSelectionStyleNone:UITableViewCellSelectionStyleDefault;
    if (indexPath.section == 0)
    {
        if (self.specialIndex == indexPath.row)
        {
            cell.titleLabel.textColor = RGB(251,121,143);
        }
        
        NSInteger firstSeclastRow = self.viewStyle == BMActionSheetStyleNormal || self.viewStyle == BMActionSheetStyleImage ? self.dataArray.count-1 : self.dataArray.count;
        if (firstSeclastRow == indexPath.row) {
            //最下面 底部左右圆角
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerBottomRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(5, 5)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell.bounds;
            maskLayer.path = maskPath.CGPath;
            cell.layer.mask = maskLayer;
        }
        
        if (self.viewStyle == BMActionSheetStyleNormal)
        {
            cell.titleLabel.text = self.dataArray[indexPath.row];
        }
        else if (self.viewStyle == BMActionSheetStyleTitle)
        {
            
            if (indexPath.row == 0) {
                //最上面 顶部左右圆角
                UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(5, 5)];
                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
                maskLayer.frame = cell.bounds;
                maskLayer.path = maskPath.CGPath;
                cell.layer.mask = maskLayer;
                
                cell.titleLabel.text = self.title ? : @"";
                cell.titleLabel.textColor = RGB(80,60,40);
            }
            else{
                cell.titleLabel.text = self.dataArray[indexPath.row-1];
            }
        }
        else
        {
            
            NSInteger index = (self.title) ? indexPath.row - 1 : indexPath.row;
            if (index >= 0)
            {
                cell.imageView.image = self.imageArray[index];
            }
            
            cell.titleLabel.text = (indexPath.row == 0) ? self.title : self.dataArray[indexPath.row-1];
        }
    }
    else
    {
        cell.titleLabel.text = @"取消";
        cell.layer.cornerRadius = 5.f;
        cell.layer.masksToBounds = YES;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.title && indexPath.section == 0 && indexPath.row == 0) {
        CGFloat height = [self.title sizeWithFont:[UIFont systemFontOfSize:16.f] maxW:APP_WIDTH - 40].height + 20;
        return MAX(height, 45);
    }else{
        return 45.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return (section == 0)?10.f:0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (0 == indexPath.section)
    {
        NSInteger index = 0;
        if (self.viewStyle == BMActionSheetStyleNormal || self.viewStyle == BMActionSheetStyleImage)
        {
            index = indexPath.row;
        }
        else
        {
            index = indexPath.row - 1;
        }
        if (index == -1)
        {
            NSLog(@"标题不能点击");
            return;
        }
        [self fadeOut];
        self.clickBlock(index);
    }
    else if (indexPath.section == 1)
    {
        NSLog(@"点击了取消");
        [self fadeOut];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - overlay
- (void)fadeIn{
    CGFloat tableViewHeight = MIN(APP_HEIGHT - 64.f, self.tableView.contentSize.height);
    self.tableView.frame = CGRectMake(10.f, 0.f, APP_WIDTH - 20.f, tableViewHeight);
    
    self.frame = CGRectMake(0.f, APP_HEIGHT, APP_WIDTH, tableViewHeight);
    BMWeakSelf
    [UIView animateWithDuration:.25f animations:^{
        weakSelf.frame = CGRectMake(0.f, APP_HEIGHT - tableViewHeight, APP_WIDTH, tableViewHeight);
    }];
}

- (void)fadeOut{
    BMWeakSelf
    [UIView animateWithDuration:.3f animations:^{
        weakSelf.frame = CGRectMake(0.f, APP_HEIGHT+CGRectGetHeight(weakSelf.frame)*0.3, APP_WIDTH, CGRectGetHeight(weakSelf.frame));
    } completion:^(BOOL finished) {
        if (finished) {
            [weakSelf.overlayControl removeFromSuperview];
            weakSelf.overlayControl = nil;
            [weakSelf removeFromSuperview];
        }
    }];
}

- (void)layoutSubviews{

    [super layoutSubviews];
    
    CGFloat tableViewHeight = MIN(APP_HEIGHT - 64.f, self.tableView.contentSize.height);
    self.tableView.frame = CGRectMake(10.f, 0.f, APP_WIDTH - 20.f, tableViewHeight);
    self.frame = CGRectMake(0.f, APP_HEIGHT - tableViewHeight, SCREEN_WIDTH, tableViewHeight);
}

- (void)show{
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
    [keywindow addSubview:self.overlayControl];
    [keywindow addSubview:self];
    [self fadeIn];
}

- (void)dismissActionSheet{
    NSLog(@"点击遮罩层 开始消失");
    [self fadeOut];
}

#pragma mark - lazy getter
- (UITableView *)tableView{
    if (!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        [self addSubview:_tableView];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BMActionAlertCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([BMActionAlertCell class])];
    }
    return _tableView;
}

- (UIControl *)overlayControl{
    if (!_overlayControl){
        _overlayControl = [[UIControl alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        _overlayControl.backgroundColor = [UIColor colorWithRed:.16f green:.17f blue:.21f alpha:.5f];
        [_overlayControl addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventTouchUpInside];
        _overlayControl.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
    }
    return _overlayControl;
}

- (void)dealloc{
    NSLog(@"[%@]销毁了",NSStringFromClass([self class]));
}
@end
